package cn.xyy.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import cn.xyy.common.domain.system.auth.UserInfo;
import cn.xyy.common.utils.HttpUtils;
import cn.xyy.common.utils.LoggerUtil;

/**
 * 请求日志记录器
 * 
 * @author xyy
 *
 */
@Component
public class LogFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 当前仅记录日志，后续可以添加日志队列，来过滤请求慢的接口
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		long startTime = System.currentTimeMillis();
		String ip = HttpUtils.getIpAddr(httpRequest);
		String api = httpRequest.getRequestURL().toString();
		String user = "";
		UserInfo userInfo = AuthUserHolder.getUserInfo();
		if (userInfo != null) {
			user = userInfo.getRealName();
		}
		// 执行
		chain.doFilter(request, response);

		long executeTime = System.currentTimeMillis() - startTime;

		LoggerUtil.info("来自IP地址：{}，请求接口：{}，用户：{}，请求耗时：{}ms", ip, api, user, executeTime);

	}

}
